/*
 *  Copyright (C) 2011 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_Favorites.java
 *
 * Created on 23/01/2011, 18:23:12
 */
package kuasar.plugin.vmcreator.gui.Favorites;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileFilter;
import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import kuasar.plugin.Intercom.ODR;
import kuasar.plugin.utils.XML;
import kuasar.plugin.vmcreator.Config;
import kuasar.plugin.vmcreator.gui.pn_Main;
import kuasar.plugin.vmcreator.gui.tooltasks.AddHost.Namespace.keyMaps;
import kuasar.plugin.vmcreator.utils.Others;
import org.jdom.Element;

/**
 *
 * @author jnavalon
 */
public class pn_Favorites extends kuasar.plugin.classMod.AbstractPanel {

    DefaultListModel model = new DefaultListModel();
    pn_Main parent;

    /** Creates new form pn_Favorites */
    public pn_Favorites(pn_Main parent) {
        this.parent=parent;
        initComponents();
        pn_Aux.setVisible(false);
        lbl_Info.setVisible(false);
        txt_Filter.setVisible(false);
        scp_Favorites.getViewport().setOpaque(false);
        lst_Favorites.setCellRenderer(new Lst_Favorites_CellRender());
        lst_Favorites.setModel(model);
        loadData(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pn_Aux = new javax.swing.JPanel();
        lbl_Name = new javax.swing.JLabel();
        txt_Name = new javax.swing.JTextField();
        lbl_Info = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        scp_Favorites = new javax.swing.JScrollPane();
        lst_Favorites = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        lbl_Title = new javax.swing.JLabel();
        pn_Search = new javax.swing.JPanel();
        lbl_Search = new javax.swing.JLabel();
        txt_Filter = new javax.swing.JTextField();

        setBackground(new java.awt.Color(204, 0, 51));
        setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        setOpaque(false);
        addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                formAncestorResized(evt);
            }
        });

        pn_Aux.setBackground(new java.awt.Color(255, 255, 102));
        pn_Aux.setOpaque(false);

        lbl_Name.setForeground(new java.awt.Color(205, 205, 205));
        lbl_Name.setText("Name:");

        txt_Name.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt_NameKeyReleased(evt);
            }
        });

        lbl_Info.setForeground(java.awt.Color.pink);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/remove.png"))); // NOI18N
        jLabel1.setToolTipText("Remove Favorite");
        jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout pn_AuxLayout = new javax.swing.GroupLayout(pn_Aux);
        pn_Aux.setLayout(pn_AuxLayout);
        pn_AuxLayout.setHorizontalGroup(
            pn_AuxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbl_Info, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
            .addGroup(pn_AuxLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txt_Name, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pn_AuxLayout.createSequentialGroup()
                .addComponent(lbl_Name, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap())
        );
        pn_AuxLayout.setVerticalGroup(
            pn_AuxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pn_AuxLayout.createSequentialGroup()
                .addGroup(pn_AuxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_Name)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txt_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(lbl_Info))
        );

        scp_Favorites.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        scp_Favorites.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scp_Favorites.setViewportBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        lst_Favorites.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        lst_Favorites.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lst_Favorites.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        lst_Favorites.setOpaque(false);
        lst_Favorites.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lst_FavoritesValueChanged(evt);
            }
        });
        scp_Favorites.setViewportView(lst_Favorites);

        jPanel1.setOpaque(false);

        lbl_Title.setForeground(new java.awt.Color(205, 205, 205));
        lbl_Title.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/star.png"))); // NOI18N
        lbl_Title.setText("Favorites");

        pn_Search.setOpaque(false);

        lbl_Search.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/search.png"))); // NOI18N
        lbl_Search.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        lbl_Search.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        lbl_Search.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lbl_SearchMouseReleased(evt);
            }
        });

        txt_Filter.setFont(new java.awt.Font("Ubuntu", 0, 12));
        txt_Filter.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt_FilterKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout pn_SearchLayout = new javax.swing.GroupLayout(pn_Search);
        pn_Search.setLayout(pn_SearchLayout);
        pn_SearchLayout.setHorizontalGroup(
            pn_SearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pn_SearchLayout.createSequentialGroup()
                .addContainerGap(129, Short.MAX_VALUE)
                .addComponent(lbl_Search, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(pn_SearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pn_SearchLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(txt_Filter, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        pn_SearchLayout.setVerticalGroup(
            pn_SearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pn_SearchLayout.createSequentialGroup()
                .addGap(3, 3, 3)
                .addComponent(lbl_Search)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(pn_SearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pn_SearchLayout.createSequentialGroup()
                    .addGap(1, 1, 1)
                    .addComponent(txt_Filter, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addGap(2, 2, 2)))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(lbl_Title)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_Search, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pn_Search, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbl_Title, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scp_Favorites, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pn_Aux, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scp_Favorites, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_Aux, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formAncestorResized
        this.updateUI();
    }//GEN-LAST:event_formAncestorResized

    private void lbl_SearchMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl_SearchMouseReleased
        lbl_Search.setVisible(false);
        txt_Filter.setVisible(true);
        txt_Filter.requestFocus();
    }//GEN-LAST:event_lbl_SearchMouseReleased

    private void txt_FilterKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_FilterKeyReleased
        switch (evt.getKeyCode()) {
            case KeyEvent.VK_ESCAPE:
                lbl_Search.setVisible(true);
                txt_Filter.setVisible(false);
                txt_Filter.setText("");
                loadData(null);
                break;
            default:
                loadData(txt_Filter.getText().toLowerCase());
        }
        if(pn_Aux.isVisible())pn_Aux.setVisible(false);
    }//GEN-LAST:event_txt_FilterKeyReleased

    private void lst_FavoritesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lst_FavoritesValueChanged
        if (lst_Favorites.getSelectedIndices().length > 0) {
            pn_Aux.setVisible(true);
            lbl_Name.setText("Name for " + ((Object[]) lst_Favorites.getSelectedValue())[1].toString());
            txt_Name.setText("");
            txt_Name.setBackground(Color.white);
            txt_Name.setEnabled(true);
            lbl_Info.setVisible(false);
            txt_Name.requestFocus();
        }
    }//GEN-LAST:event_lst_FavoritesValueChanged

    private void txt_NameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_NameKeyReleased
        switch(evt.getKeyCode()){
            case KeyEvent.VK_ESCAPE:
                pn_Aux.setVisible(false);
                lst_Favorites.clearSelection();
                break;
            case KeyEvent.VK_ENTER:
                if(addFavorite(((Object[])lst_Favorites.getSelectedValue())[1].toString())){
                    pn_Aux.setVisible(false);
                    lst_Favorites.clearSelection();
                }
                break;
        }
    }//GEN-LAST:event_txt_NameKeyReleased

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
       if(lst_Favorites.getSelectedIndices().length==0) return;
            String path = ((String) kuasar.plugin.Intercom.ODR.getValue("$PLUGINDIR")) + File.separator + kuasar.plugin.vmcreator.Config.path + File.separator + kuasar.plugin.vmcreator.Config.favorites;
            File file = new File(path+File.separator+((Object[])lst_Favorites.getSelectedValue())[1].toString()+".bin");
            if(file.exists()){
                file.delete();
            }
            reload();
            pn_Aux.setVisible(false);
    }//GEN-LAST:event_jLabel1MouseClicked

    public void reload() {
        loadData(null);
    }

    private boolean addFavorite(String id) {
        String path = ((String) kuasar.plugin.Intercom.ODR.getValue("$PLUGINDIR")) + File.separator + kuasar.plugin.vmcreator.Config.path + File.separator + kuasar.plugin.vmcreator.Config.favorites;
        File src = new File(path+File.separator+id+".bin");
        if(!src.exists()){
            lbl_Info.setVisible(true);
            lbl_Info.setText("File not Found... Reloaded!");
            txt_Name.setEnabled(false);
            lst_Favorites.clearSelection();
            reload();
            return false;
        }
        path = ((String) kuasar.plugin.Intercom.ODR.getValue("$PLUGINDIR")) + File.separator + kuasar.plugin.vmcreator.Config.path + File.separator + kuasar.plugin.vmcreator.Config.virtualmachine;
  
        if (txt_Name.getText().trim().isEmpty()) {
            txt_Name.setBackground(Color.pink);
            return false;
        }

        if(!XML.isCorrectName(txt_Name.getText())){
            lbl_Name.setVisible(true);
            lbl_Info.setText("Only alfanumeric and spaces.");
            txt_Name.setBackground(Color.pink);
            return false;
        }
        Element root = XML.getElementOnPath(parent.onAir,(Element) ODR.getValue(Config.path + "." + Config.network));
        String name = XML.adaptName(txt_Name.getText());
        Element node = root.getChild(name);
        if (node != null) {
            lbl_Info.setVisible(true);
            lbl_Info.setText("Name exists!");
            return false;
        }
        File dest =Others.nextFileAvailable(path);
        Others.FileCopy(src, dest);
        HashMap<String,Object> map = Others.getVM(dest);
        Others.saveXML(name, dest, map, parent.onAir, false);
        parent.reloadList();
        return true;

    }

    private void loadData(String filter) {
        model.removeAllElements();
        File dir = new File(((String) kuasar.plugin.Intercom.ODR.getValue("$PLUGINDIR")) + File.separator + kuasar.plugin.vmcreator.Config.path + File.separator + kuasar.plugin.vmcreator.Config.favorites);
        if (!dir.exists()) {
            return;
        }
        if (!dir.isDirectory()) {
            System.err.println("Error: File isn't a directory! :: " + dir.getPath());
            return;
        }
        for (File file : dir.listFiles(new BinFilter())) {
            if (filter == null || file.getName().toLowerCase().substring(0, file.getName().lastIndexOf('.')).contains(filter)) {
                if (file.isFile()) {
                    loadFile(file);
                }
            }
        }
        lst_Favorites.updateUI();
    }

    private void loadFile(File file) {
        {
                HashMap<String, Object> map = Others.getVM(file);
                if(map==null)return;
                Object[] data = new Object[2];
                data[0] = new ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/netlist/" + Others.getIcon((Integer) map.get(keyMaps.OS + ".id"))));
                data[1] = file.getName().substring(0, file.getName().lastIndexOf('.'));
                model.addElement(data);
                lst_Favorites.setModel(model);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbl_Info;
    private javax.swing.JLabel lbl_Name;
    private javax.swing.JLabel lbl_Search;
    private javax.swing.JLabel lbl_Title;
    private javax.swing.JList lst_Favorites;
    private javax.swing.JPanel pn_Aux;
    private javax.swing.JPanel pn_Search;
    private javax.swing.JScrollPane scp_Favorites;
    private javax.swing.JTextField txt_Filter;
    private javax.swing.JTextField txt_Name;
    // End of variables declaration//GEN-END:variables
}

class BinFilter implements FileFilter {

    public boolean accept(File pathname) {

        if (pathname.getName().endsWith(".bin")) {
            return true;
        }
        return false;
    }
}
